﻿//Copyright (c) Microsoft Corporation. All rights reserved.

using Microsoft.Ted.Wacel;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;

namespace Microsoft.Ted.Wacel.Demo.Worker
{
    public class SystemperfMon
    {
        private bool mShouldRun = true;
        private Thread mThread;
        public void Start()
        {
            Cache.Cube cube = new Cache.Cube("CPUPerfCube");
            cube.AddDimension(Dimension.GetTimeDimensionMonthDayHour5Minutes(DateTime.Now.Year));
            cube.AddDimension(Dimension.CreateFreeDimension("CPU"));
            mThread = new Thread(new ThreadStart(() =>
                {
                    int CPUCount = Environment.ProcessorCount;
                    PerformanceCounter[] counters = new PerformanceCounter[CPUCount + 1];
                    string[] names = new string[CPUCount + 1];
                    for (int i = 0 ; i < CPUCount; i++)
                    { 
                        counters[i] = new PerformanceCounter("Processor", "% Processor Time", i.ToString());
                        names[i] = "CPU" + i.ToString();
                    }
                    counters[CPUCount] = new PerformanceCounter("Processor", "% Processor Time", "_Total");
                    names[CPUCount] = "CPUTotal";
                    while (mShouldRun)
                    {
                        List<dynamic> datapoints = new List<dynamic>();
                        for (int i = 0; i < CPUCount+1; i++)
                            datapoints.Add(new { Time = Dimension.Get5MinuteTimeKey(DateTime.UtcNow), CPU = names[i], Value = (double)counters[i].NextValue() });
                        cube.Update(datapoints);
                        Thread.Sleep(500);
                    }
                }));
            mThread.Start();
        }
        public void Stop()
        {
            mShouldRun = false;
            mThread.Join();
        }
    }
}
